package annotation.demo.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import struts.annotation.action.ActionInterface;
import struts.annotation.util.FindRequestMappingAction;


/**
 * Servlet implementation class ActionServlet
 */
@WebServlet("/ActionServlet")
public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ActionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    private String getPath(String servletPath) {
    	return servletPath.split("\\.")[0];
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取请求头的请求路径
		String path=this.getPath(request.getServletPath());
		System.out.println(path);
		Class<?> clazz=FindRequestMappingAction.getClassByRequestMapping(path);
		ActionInterface action=null;
		String url="";
		try {
			action =(ActionInterface) clazz.newInstance();
			url=action.excute(request,response);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		//获得了转发器对象
		RequestDispatcher dis=request.getRequestDispatcher(url);
		dis.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
